package com.core.manager.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import ch.qos.logback.classic.Logger;

import com.core.manager.UserMng;
import com.core.dao.UserDAO;
import com.core.dao.UserDAOImpl;
import com.core.entity.User;
import com.core.entity.UserExample;
import com.core.entity.UserExample.Criteria;

@Service
public class UserMngImpl implements UserMng {
	private static final Logger log = (Logger) LoggerFactory
			.getLogger(UserMngImpl.class);

	@Resource(type = UserDAOImpl.class)
	private UserDAO userDao;

	@Override
	public User login(String userName, String pwd)
			throws UsernameNotFoundException, UserRepeatingDataException,
			UserPwdNotEqualException {
		Assert.notNull(userName);
		Assert.notNull(pwd);
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUserNameEqualTo(userName);
		List<User> users = userDao.selectByExample(example);
		if (users.size()==0) {
			log.error("username:" + userName + " 系统不存在该管管理员");
			throw new UsernameNotFoundException("不存在此管理员");
		} else if (users.size() > 1) {
			log.error("username:" + userName + ",系统里面存在重复数据");
			throw new UserRepeatingDataException("系统数据异常,存在重复的管理员");
		} else if (!StringUtils.equals(pwd, users.get(0).getPassWord())) {
			throw new UserPwdNotEqualException("用户名密码错误");
		}
		return users.get(0);
	}

	/**
	 * 自定义异常 用户不存在
	 * 
	 * @author hp
	 * 
	 */
	public class UsernameNotFoundException extends Exception {
		public UsernameNotFoundException() {
		}

		public UsernameNotFoundException(String msg) {
			super(msg);
		}
	}

	/**
	 * 自定义异常 ，用户名重复
	 * 
	 * @author Administrator
	 * 
	 */
	public class UserRepeatingDataException extends Exception {
		public UserRepeatingDataException() {
		}

		public UserRepeatingDataException(String msg) {
			super(msg);
		}
	}

	public class UserPwdNotEqualException extends Exception {
		public UserPwdNotEqualException() {
		}

		public UserPwdNotEqualException(String msg) {
			super(msg);
		}
	}
}
